import java.io.*; import java.util.*; /** * Class: TrivialExample2. *
Description: This trivial examples illustrates how to use * the buildFromInfix and evaluate methods in the ExprEvaluator * class. This example uses evaluate(vars) where vars is an array * of values for all 26 variables. *

* The techniques in this example may be * useful when several variables are used. See Trivial Example3 for an * example using the getValueOf(var, value), setValueOf(var), * and evaluate() methods. * TrivialExample uses techniques suitable when only the "common" variables * t, x, and y are used. *

* To evaluate prefix or postfix expressions, simply replace "buildFromInfix" by * "buildFromPrefix" or "buildFromPostfix". *

* Requires: *
ExprEvaluator.java *
EasyFormat.java *
DoubleScanner.java * @version Date: 6/10/2008 * @author James Brink, brinkje@plu.edu */ public class TrivialExample2 { double [] vars = new double[26]; // all values set to 0 initially double infixVal; String infix; ExprEvaluator evaluator = new ExprEvaluator(); Scanner scan = new Scanner(System.in); /** * Constructor for TrivialExample2. * * Note: in this case, the expression uses variables a, x and y. The * values of the variables are stored in an array "vars" which is * passed by an evaluate method. */ public TrivialExample2() { // get input System.out.print("Enter the value for a: "); vars['a' - 'a'] = scan.nextDouble(); System.out.print("Enter the value for x: "); vars['x' - 'a'] = scan.nextDouble(); System.out.print("Enter the value for y: "); vars['y' - 'a'] = scan.nextDouble(); scan.nextLine(); // read rest of line System.out.print("Enter the expression to be evaluated: "); infix = scan.nextLine(); // evaluate expression and print the results try { evaluator.buildFromInfix(infix); System.out.println("The results are"); infixVal = evaluator.evaluate(vars); // // variable values may have changed so use evaluator.getValueOf System.out.println("a = " + evaluator.getValueOf('a') + ", x = " + evaluator.getValueOf('x') + ", y = " + evaluator.getValueOf('y') + ", expression = " + infixVal); }catch (Exception e) { System.out.println ("Error: namely: " + e); } } // constructor TrivialExample2 /** * Trivial main program that starts the application. */ public static void main (String args[]) { TrivialExample2 app = new TrivialExample2(); System.exit(0); } // end main } // class TrivialExample2